const mysql = require('mysql2/promise');

class DB {
  constructor(options) {
    this.options = options;
  }
  async init() {
    this.con = await mysql.createConnection(this.options);
  }

  async getTables() {
    var tables = [];
    var sql = `select * from information_schema.tables where table_schema = '${this.options.database}'`;
    var res = await this.con.execute({
      sql: sql
    });

    for (let i = 0; i < res[0].length; i++) {
      var tableName = res[0][i][`TABLE_NAME`];
      if (!tableName.startsWith('v_')) {
        tables.push({ name: tableName, comment: res[0][i][`TABLE_COMMENT`] });
      }
    }
    return tables;
  }

  async getFields(tableName) {
    var fields = [];
    var sql = `select * from information_schema.columns where table_schema = '${this.options.database}' and table_name='${tableName}'`;
    var res = await this.con.execute({
      sql: sql
    });
    for (let i = 0; i < res[0].length; i++) {
      fields.push({
        name: res[0][i].COLUMN_NAME,
        type: res[0][i].DATA_TYPE,
        comment: res[0][i].COLUMN_COMMENT
      });
    }
    return fields;
  }
}

exports = module.exports = DB;
